import 'package:flutter/material.dart';

class ListPage1 extends StatelessWidget {
  const ListPage1({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Nested ExpansionPanelList',
      home: Scaffold(
        appBar: AppBar(title: const Text('Nested ExpansionPanelList')),
        body: const NestedExpansionPanelList(),
      ),
    );
  }
}

class NestedExpansionPanelList extends StatefulWidget {
  const NestedExpansionPanelList({super.key});

  @override
  _NestedExpansionPanelListState createState() =>
      _NestedExpansionPanelListState();
}

class _NestedExpansionPanelListState extends State<NestedExpansionPanelList> {
  final List<PanelItem> _data = generateData();

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: _buildPanelList(_data),
    );
  }

  Widget _buildPanelList(List<PanelItem> items) {
    return ExpansionPanelList(
      expansionCallback: (int index, bool isExpanded) {
        setState(() {
          items[index].isExpanded = isExpanded;
          print('${items[index].isExpanded}');
        });
      },
      children: items.map((PanelItem item) {
        return ExpansionPanel(
          // canTapOnHeader: true,
          headerBuilder: (BuildContext context, bool isExpanded) {
            return ListTile(
              title: Text(item.title),
            );
          },
          body: item.children.isNotEmpty
              ? Padding(
            padding: const EdgeInsets.only(left: 16.0),
            child: _buildPanelList(item.children),
          )
              : const ListTile(title: Text('No more children')),
          isExpanded: item.isExpanded,
        );
      }).toList(),
    );
  }
}

class PanelItem {
  final String title;
  bool isExpanded;
  final List<PanelItem> children;

  PanelItem({
    required this.title,
    this.isExpanded = false,
    this.children = const [],
  });
}

// 示例数据生成
List<PanelItem> generateData([int depth = 3]) {
  if (depth == 0) return [];
  return List.generate(
    3,
        (index) => PanelItem(
      title: 'Panel $index at depth $depth',
      children: generateData(depth - 1),
    ),
  );
}
